<?php


namespace app\astrteam\controller\v1;


use app\astrteam\controller\AstrTeamAuth;
use app\common\lib\AliOss;
use OSS\Core\OssException;
use think\response\Json;

class Upload extends AstrTeamAuth
{
    protected $pathType = [
        1 => 'astr_team/upload/invoice', // 发票信息
    ];

    /**
     * 文件上传大小
     * @var int
     */
    protected $file_max_size = 10485760; // 1024*1024*10=10485760  10M

    /**
     * 图片上传
     * @return Json
     */
    public function upload(): Json
    {
        $type = input('type/d', 1);

        $path = $this->pathType[$type] ?? '';

        if (!$path)
        {
            return show(config('code.error'), '上传类型异常');
        }

        $file = request()->file('file');

        if (isset($file))
        {
            $config = ['size' => $this->file_max_size, 'ext' => 'jpg,png,jpeg,pdf'];
            // tp5 文件上传验证
            $info = $file->validate($config)->oss($path);
            if (!$info)
            {
                return show(10034, $file->getError());
            }
            // 获取文件名
            $filename = $info->get_filename();
            // 字符串方式上传图片
            $content = file_get_contents($info->get_tmpname());

            try
            {
                $aliOss = AliOss::getInstance();
                $aliOss->ossUpload($filename, $content);
                if (in_array($type, [1], true))
                {   // 设置文件私有化
                    $aliOss->setFileAuthPri($filename);
                }
            }
            catch (OssException $e)
            {
                return show(10034, $e->getMessage());
            }
        } else
        {
            return show(10033, 'File is not exited.');
        }

        $msg = '上传成功';

        return show(config('code.success'), $msg, [
            'path' => '/' . $filename,
            'private_url' => $this->getOssPrivateUrl('/' . $filename),
        ]);
    }
}
